import React from 'react';
import {connect} from 'dva/index';
import {Button, DatePicker, Drawer, Form, Input, Popconfirm, Select, Table, Tabs, Tag} from 'antd';
import styles from '../index.less';


import ViewTitle from '../../components/ViewTitle';
import FormBase from '../../components/Base/FormBase';
import notify from "../../components/NotificationExtra";
import {FormField, ModalView, SearchForm} from 'antd-extra';
import moment from 'moment';
import 'moment/locale/zh-cn';
import ModalCreateOrEditWork from "./modal/ModalCreateOrEditWork";

import ModalWorkDetail from "./modal/ModalWorkDetail";
import TimerWorkSetting from "./TimerWorkSetting";

moment.locale('zh-cn');
const _ = require('lodash');
const table = 'Work';
const title = '工作任务';

@Form.create()
@connect(({user, global, work}) => ({...user, ...global, ...work}))
export default class Index extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {dispatch} = this.props;
    const {userCode, username, isAdmin} = this.getLoginInfo();

    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    if (payload.isEnded === '全部') delete payload.isEnded;
    if (payload.isEnded === '已完结') payload.isEnded = true;
    if (payload.isEnded === '未完结') payload.isEnded = false;
    payload.userCode = userCode;
    payload.createUser = username;
    payload.isAdmin = isAdmin;

    dispatch({
      type: 'global/getModel',
      payload: {table}
    });
    dispatch({
      type: 'work/findWorkMany',
      payload
    });

  }

  columns = () => {
    // const model = this.props[`${table}Model`];
    // if (!model) return [];
    const {userCode, username} = this.getLoginInfo();
    // const temp = this.getTableColumns(model);
    const temp = [];
    temp.push(
      {title: '任务编码', dataIndex: 'code', key: 'code', width: 180},
      {title: '创建人', dataIndex: 'createUsername', key: 'createUsername'},
      {
        title: '创建时间', dataIndex: 'createdTs', key: 'createdTs',
        render: (value) => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      },
      {title: '任务名称', dataIndex: 'workName', key: 'workName'},
      {
        title: '责任人', dataIndex: 'workList', key: 'workList', render: (value, record) => {
          const {workList = []} = record;
          let v = "";
          _.map(workList, (value, key) => {
            v += value.username + " ";
          });
          return <div>{v}</div>;
        }
      },
      // {title: '事项', dataIndex: 'desc', key: 'desc', ellipsis: true},
      {
        title: '要求完成时间',
        dataIndex: 'requiredCompletionDate',
        key: 'requiredCompletionDate',
        render: (text, record) => {
          return text ? <div>{moment(text).format('YYYY-MM-DD')}</div> : <div></div>;
        }
      },
      {
        title: '实际完成时间',
        dataIndex: 'completionDate',
        key: 'completionDate',
        render: (text, record) => {
          return text ? <div>{moment(text).format('YYYY-MM-DD')}</div> : <div></div>;
        }
      },
      // {
      //   title: '完成情况',
      //   dataIndex: 'completionDesc',
      //   key: 'completionDesc', ellipsis: true
      // },

      {
        title: '是否逾期', dataIndex: 'isOverdue', key: 'isOverdue',
        render: (value, record) => {
          const {completionDate, requiredCompletionDate, isEnded} = record;
          const day1 = moment(requiredCompletionDate).format('YYYY-MM-DD');
          const day2 = moment().format('YYYY-MM-DD');

          let _str = moment(day2).valueOf() > moment(day1).valueOf() ? <Tag color={'#f00'}>已逾期</Tag> :
            <Tag color={'#108ee9'}>未逾期</Tag>;
          let str = isEnded ? <Tag color={'#87d068'}>已完成</Tag> : _str;
          return <div>{str}</div>;
        }
      }, {
        title: '是否完成', dataIndex: 'isEnded', key: 'isEnded',
        render: (value, record) => {
          const {isTimer, needConfirm} = record;
          if (isTimer && !needConfirm) {
            return <Tag color={'#87d068'}>自动确认</Tag>;
          }
          return value ? <Tag color={'#87d068'}>是</Tag> : <Tag color={'#108ee9'}>否</Tag>;
        }
      },
      {
        title: '是否关联任务', dataIndex: 'relationWorkCode', key: 'relationWorkCode',
        render: (value) => {
          return value ? <Tag color={'green'}>是</Tag> : <Tag color={"blue"}>否</Tag>;
        }
      },
      {
        title: '是否定时任务', dataIndex: 'isTimerWork', key: 'isTimerWork',
        render: (value) => {
          return value ? <Tag color={'green'}>是</Tag> : <Tag color={"blue"}>否</Tag>;
        }
      },
      {
        title: '操作', dataIndex: 'operation', key: 'operation',
        width: 240, fixed: 'right',
        render: (value, record) => {
          const {code, createUser, timerMethod, isEnded, isAdmin} = record;
          const _record = _.clone(record);
          _record.relationWorkCode = code;
          return (
            <span>
                   {<a style={{marginRight: '6px'}}
                       onClick={() => {
                         this.setState({showDetail: true, record});
                       }}
                   >详情</a>}
              {<a style={{marginRight: '6px'}} disabled={isEnded}
                  onClick={() => this.onCreateOrEdit({record, isTimer: timerMethod})}
              >编辑</a>}
              {<Popconfirm
                title="确认删除"
                onConfirm={() => {
                  this.props.dispatch({
                    type: 'work/deleteWork',
                    payload: {code}
                  }).then(res => {
                    this.requestReturn(res);
                    this.componentDidMount();
                  });
                }}
                okText="是"
                cancelText="否"
              >
                <a style={{marginRight: '6px'}} disabled={!isAdmin || isEnded}>删除</a>
              </Popconfirm>}
              {/*{<a style={{marginRight: '6px'}} disabled={!isAdmin}*/}
              {/*    onClick={() => this.onCreateRelationWork(record)}*/}
              {/*>创建关联任务</a>}*/}
            </span>
          );
        }
      });

    return temp;
  };

  onCreateOrEdit = (opt) => {
    const {record, isTimer = false} = opt;
    const type = record ? 'work/updateWork' : 'work/createWork';
    const login = this.getLoginInfo();
    ModalView.open(ModalCreateOrEditWork,
      {
        title,
        width: '1080px'
      }, {
        table, isTimer, record,
        callback: (payload) => {
          payload.isAdmin = login.isAdmin;
          this.props.dispatch({
            type,
            payload
          }).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
        }
      });
  };

  onCreateRelationWork = (record) => {
    const type = 'work/createWork';
    const login = this.getLoginInfo();
    ModalView.open(ModalCreateOrEditWork,
      {
        title,
        width: '1080px'
      }, {
        table, relationWorkCode: record.code,
        callback: (payload) => {
          payload.isAdmin = login.isAdmin;
          payload.relationWorkCode = record.code;
          this.props.dispatch({
            type,
            payload
          }).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
        }
      });
  };

  render() {
    const {works, _notify, form} = this.props;
    const {showDetail, record} = this.state;
    const loginInfo = this.getLoginInfo();
    //  console.log('log info', loginInfo);
    const {userType, isAdmin = false} = loginInfo;
    if (_notify) {
      notify(_notify);
    }
    const model = this.props[`${table}Model`];

    return (
      <Form className={styles.content}>
        <Tabs defaultActiveKey="1">
          <Tabs.TabPane key={"1"} tab={"任务列表"}>
            <ViewTitle
              title={`${title}列表`}
              level={1}
              actions={[
                userType === 'admin' &&
                <Button type="primary" onClick={() => this.onCreateOrEdit({isTimer: false})}>添加</Button>
              ]
              }></ViewTitle>
            <SearchForm
              style={{marginLeft: '6px', marginRight: '6px'}}
              onSearch={() => {
                this.state.current = 1;
                this.componentDidMount();
              }}
              onReset={this.handleReset}
              cols={3}
              min={6}
              expandText="展开"
              form={form}
            >
              {[
                <FormField
                  label={'任务编码'}
                  name={'code'}

                >
                  <Input></Input>
                </FormField>,
                <FormField
                  label={'任务名称'}
                  name={'workName'}
                >
                  <Input></Input>
                </FormField>,
                // <FormField
                //   label={'详细内容'}
                //   name={'desc'}
                //
                // >
                //   <Input></Input>
                // </FormField>,
                <FormField
                  label={'是否完结'}
                  name={'isEnded'}
                  initialValue={'全部'}
                >
                  <Select style={{width: '100%'}}
                  >{this.getOption2(['全部', '已完结', '未完结'])}</Select>
                </FormField>,
                <FormField
                  label={'是否逾期'}
                  name={'isOverdue'}
                  initialValue={'全部'}
                >
                  <Select style={{width: '100%'}}
                  >{this.getOption2(['全部', '已逾期', '未逾期'])}</Select>
                </FormField>,
                <FormField
                  label={'责任人'}
                  name={'workUsername'}
                >
                  <Input></Input>
                </FormField>,
                <FormField
                  label={'线下人员'}
                  name={'offlineMan'}
                >
                  <Input></Input>
                </FormField>,
                <FormField
                  label={'创建时间'}
                  name={'createdTs'}
                  initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndMonth()]}
                >
                  <DatePicker.RangePicker></DatePicker.RangePicker>
                </FormField>
              ]}
            </SearchForm>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.columns()}
              dataSource={works}
              scroll={{x: true}}
              pagination={{
                current: this.state.current,
                total: this.state.total,
                showSizeChanger: true,
                onChange: page => {
                  this.state.current = page;
                  this.componentDidMount();
                },
                onShowSizeChange: (current, pageSize) => {
                  this.state.current = 1;
                  this.state.pageSize = pageSize;
                  this.componentDidMount();
                }
              }}
            ></Table>
            {showDetail && <Drawer
              visible={showDetail}
              title={`工作任务`}
              placement="left"
              width={'80%'}
              style={{padding: 0}}
              // maskClosable={false}
              onClose={() => {
                this.setState({showDetail: false});
                this.componentDidMount();
              }}
            >
              <ModalWorkDetail
                record={record}
              > </ModalWorkDetail>
            </Drawer>}
          </Tabs.TabPane>
          {isAdmin && <Tabs.TabPane tab={"定时任务设置"} key={"2"}>
            {<TimerWorkSetting></TimerWorkSetting>}
          </Tabs.TabPane>}
        </Tabs>
      </Form>
    );
  }
}
